package com.qlmy.cn.api

import com.qlmy.cn.helper.mohsi.MOSHI
import com.qlmy.cn.utils.Logger
import com.wbs.shop.nuby.BuildConfig
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

val SERVICE: ApiService get() = ApiHelper.getService()
val GDGRAIN_SERVICE: ApiService get() = ApiHelper.getGdgrainService()

/**
 *   @auther : zhoucl
 *   time   : 2017/09/04
 */
object ApiHelper {
    private const val TIME_OUT = 60L
    private var apiService: ApiService? = null
    private var gdgrainService: ApiService? = null// 省平台地址

    fun getService(timeout: Long? = null): ApiService {
        if (timeout != null) {
            return createService(timeout)
        } else {
            if (apiService == null) {
                apiService = createService(TIME_OUT)
            }
            return apiService!!
        }
    }

    fun getGdgrainService(): ApiService {
        if (gdgrainService == null) {
            gdgrainService = createService(TIME_OUT, "")
        }
        return gdgrainService!!
    }

    private fun createService(timeout: Long, baseUrl: String = "") = Retrofit.Builder()
            .client(getOkHttpClient(timeout))
            .addConverterFactory(MoshiConverterFactory.create(MOSHI))
            .baseUrl(baseUrl)
            .build()
            .create(ApiService::class.java)

    private fun getOkHttpClient(timeout: Long): OkHttpClient {
        return OkHttpClient.Builder()
                .connectTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .readTimeout(timeout, TimeUnit.SECONDS)
                .proxy(Proxy.NO_PROXY)
                .addInterceptor(ConvertInterceptor())
                .apply {
                    if (BuildConfig.DEBUG) {
                        addNetworkInterceptor(getHttpLoggingInterceptor())
                    }
                }
                .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
                .build()
    }

    private fun getHttpLoggingInterceptor() = HttpLoggingInterceptor { Logger.e("Api请求==>$it") }.apply { setLevel(HttpLoggingInterceptor.Level.BODY) }

    fun reset() {
        apiService = null
    }
}